package com.github.tetrisgame.ui.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.github.tetrisgame.utils.UIUtils;

public class VerifyView extends View {
    private int CreamApricot = Color.parseColor("#F8F4E3");
    private int ClearSkyBlue = Color.parseColor("#87CEEB");
    private int MintGreen = Color.parseColor("#98D7C2");
    private int mSize = UIUtils.dp2px(30);
    private int gridCount = 6;
    private int mGap = UIUtils.dp2px(10);
    private int mRadius = UIUtils.dp2px(10);
    private int lightWidth = UIUtils.dp2px(2);
    private RectF rectF = new RectF();
    private Paint lightPaint = new Paint();
    private Paint textPaint = new Paint();
    private Paint gridPaint = new Paint();

    private Paint selectedGridPaint = new Paint();
    private onGetPasswordListener getPasswordListener;
    private SpannableStringBuilder text = new SpannableStringBuilder();
    private boolean isLight = false;
    private int lightIndex = text.length();
    public VerifyView(Context context) {
        this(context,null);
    }

    public VerifyView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public VerifyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init(){
        setClickable(true);
        setFocusable(true);
        setFocusableInTouchMode(true);

        lightPaint.setColor(Color.BLACK);
        lightPaint.setStyle(Paint.Style.FILL);
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(UIUtils.sp2px(16));
        textPaint.setTextAlign(Paint.Align.CENTER);
        gridPaint.setColor(ClearSkyBlue);
        gridPaint.setStyle(Paint.Style.FILL);
        selectedGridPaint.setColor(MintGreen);
        selectedGridPaint.setStyle(Paint.Style.STROKE);
        selectedGridPaint.setStrokeWidth(UIUtils.dp2px(2));
        post(this::lightChange);


    }
    private void lightChange(){
        postDelayed(()->{
            postInvalidate();
            isLight = !isLight;
            lightChange();
        },500);
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        outAttrs.inputType = EditorInfo.TYPE_CLASS_PHONE;
        return super.onCreateInputConnection(outAttrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            requestFocus();
            InputMethodManager imm = (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

            imm.showSoftInput(this,0);
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode <= KeyEvent.KEYCODE_9 && keyCode >= KeyEvent.KEYCODE_0){
            if(text.length() < 6){
                char number = (char) event.getUnicodeChar();;
                text.append(number);
                lightIndex = text.length();
                invalidate();
            }
            if(text.length() == 6){
                if(getPasswordListener != null){
                    getPasswordListener.getPassword(text.toString());
                }
            }
        }
        if (keyCode == KeyEvent.KEYCODE_DEL){
            if(text.length()>0){
                text.delete(text.length() - 1,text.length());
                lightIndex = text.length();
                invalidate();

            }
        }
        return super.onKeyDown(keyCode, event);
    }
    public interface onGetPasswordListener{
        void getPassword(String code);
    }
    public void setOnGetPasswordListener(onGetPasswordListener getPasswordListener){
        this.getPasswordListener = getPasswordListener;
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        drawGrid(canvas);
        drawSelectedGrid(canvas);
        drawLight(canvas);

        drawTextString(canvas);
    }
    private void drawGrid(Canvas canvas){
        for (int i = 0; i < gridCount; i++) {
            if(i == lightIndex)continue;
            rectF.left = mGap + i * (mGap + mSize);
            rectF.top = mGap;
            rectF.right = rectF.left + mSize;
            rectF.bottom = rectF.top + mSize;
            canvas.drawRoundRect(
                    rectF,
                    mRadius,
                    mRadius,
                    gridPaint
            );
        }
    }
    private void drawSelectedGrid(Canvas canvas){
        rectF.left = mGap + lightIndex * (mGap + mSize);
        rectF.top = mGap;
        rectF.right = rectF.left + mSize;
        rectF.bottom = rectF.top + mSize;
        canvas.drawRoundRect(
                rectF,
                mRadius,
                mRadius,
                selectedGridPaint
        );
    }
    private void drawLight(Canvas canvas){
        if(isLight){
            Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
            float lightHeight = fontMetrics.descent - fontMetrics .ascent;
            rectF.left = mGap + (float) (mSize - lightWidth) /2 + lightIndex * (mGap + mSize);
            rectF.top = (getHeight() - lightHeight) / 2;
            rectF.right = rectF.left + lightWidth;
            rectF.bottom = rectF.top + lightHeight;
            canvas.drawRect(
                    rectF,
                    lightPaint
            );
        }

    }
    private void drawTextString(Canvas canvas){
        String textString = text.toString();
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();

        for (int i = 0; i < textString.length(); i++) {
            canvas.drawText(
                    textString.charAt(i) + "",
                    (float) mGap + mSize/2 + i * (mGap + mSize),
                    getHeight() / 2f -(fontMetrics.descent + fontMetrics .ascent)/2f,
                    textPaint
            );
        }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        if(widthMode == MeasureSpec.EXACTLY){
            mSize = (widthSize - (gridCount+1) * mGap) / 6;
        }
        setMeasuredDimension(mSize * gridCount + mGap * (gridCount + 1),mSize + 2 * mGap);

    }
}
